/**
 * 项目管理
 */
define(function (require, exports, module) {
    require('authorize');
    var $ = require('jquery');
    var util = require('util');
    var ui = require('ui');
    var angular = require("angular");
    var dialog = require("dialog");
    var areabox = require('areabox');
    require("angular-route");
    require('angular-interceptor');
    require("angular-ui");
    require("angular-messages");
    require('permission');
    require('service/ng_service/projectService');
    require("jqtree");
    require('global');
    require('./role_common');

    var api_prefix = G_CONFIG["api_prefix"] + "/project/project"; //api前缀

    angular.module('housesProject', [
        'ngRoute',
        'ngInterceptor',
        'ngMessages',
        'ngUI',
        'roleCommon'
    ])
        .factory('url', [
            function () {
                return {
                    //给url添加search字符串
                    addParam: function (url, search) {
                        for (var key in search) {
                            if (search.hasOwnProperty(key) && search[key]) {
                                var connecter = "&";
                                if (url.indexOf('?') === -1) {
                                    connecter = "?";
                                }
                                url += connecter + key + '=' + encodeURIComponent(search[key]);
                            }
                        }
                        return url;
                    }
                };
            }
        ])
        .factory('projectService', [
            '$http',
            'url',
            function ($http, url) {
                return {
                    getOrgList: function (options) {
                        return $http.get(G_CONFIG["api_prefix"] + 'usermanage/organization/query-all-organizations', {
                            params: {NEED_TOKEN: false}
                        })
                            .success(function (res) {
                                if (res && res.retCode == 0) {
                                    options.success(res);
                                    return;
                                }
                                options.fail && options.fail(res);
                            })
                            .error(function (res) {
                                options.fail && options.fail(res);
                            })
                    },
                    searchProjectList: function (options) {
                        var api = url.addParam(api_prefix + '/get-project-list-by-organization-id', options.search);
                        return $http.get(api, {
                            params: {NEED_TOKEN: false}
                        })
                            .success(function (res) {
                                if (res && res.retCode == 0) {
                                    options.success(res);
                                    return;
                                }
                                options.fail && options.fail(res);
                            })
                            .error(function (res) {
                                options.fail && options.fail(res);
                            })
                    },
                    moveProject: function (options) {
                        angular.extend(options.data, {NEED_TOKEN: false})
                        return $http.post(api_prefix + '/move-project-order-id', options.data)
                            .success(function (res) {
                                if (res && res.retCode == 0) {
                                    options.success(res);
                                    return;
                                }
                                options.fail && options.fail(res);
                            })
                            .error(function (res) {
                                options.fail && options.fail(res);
                            })
                    },
                    deleteProject: function (options) {
                        angular.extend(options.data, {NEED_TOKEN: false})
                        return $http.post(api_prefix + '/del-project-by-project-id', options.data)
                            .success(function (res) {
                                if (res && res.retCode == 0) {
                                    options.success(res);
                                    return;
                                }
                                options.fail && options.fail(res);
                            })
                            .error(function (res) {
                                options.fail && options.fail(res);
                            })
                    },
                    setDefaultPeriod: function (options) {
                        angular.extend(options.data, {NEED_TOKEN: false})
                        return $http.post(api_prefix + '/set-default-sub-project', options.data)
                            .success(function (res) {
                                if (res && res.retCode == 0) {
                                    options.success(res);
                                    return;
                                }
                                options.fail && options.fail(res);
                            })
                            .error(function (res) {
                                options.fail && options.fail(res);
                            })
                    },
                    queryAllOrganizations: function (options) {
                        return $http.get('/api/index.php?r=usermanage/organization/query-all-organizations', {
                            params: {NEED_TOKEN: false}
                        })
                            .success(function (res) {
                                if (res && res.retCode == 0) {
                                    options.success(res);
                                    return;
                                }
                                options.fail && options.fail(res);
                            })
                            .error(function (res) {
                                options.fail && options.fail(res);
                            })
                    },
                    getErpProjectsList: function (data, search) {
                        search = search || '';
                        data = data || {}
                        data['params'] = data['params'] || {};
                        data['params']['NEED_TOKEN'] = false;
                        return $http.get('/api/index.php?r=common/erp-interface/get-erp-project-list' + search, data)
                    },
                    getErpCompanies: function (data, search) {
                        search = search || '';
                        data = data || {}
                        data['params'] = data['params'] || {};
                        data['params']['NEED_TOKEN'] = false;
                        return $http.get('/api/index.php?r=usermanage/organization/query-all-erp-companies' + search, data)
                    },
                    checkCanBind: function (data, search) {
                        search = search || '';
                        data = data || {}
                        data['params'] = data['params'] || {};
                        data['params']['NEED_TOKEN'] = false;
                        return $http.get('/api/index.php?r=project/auth/check-has-erp' + search, data)
                    },
                    getAuthInfo: function (data, search) {
                        search = search || '';
                        data = data || {}
                        data['params'] = data['params'] || {};
                        data['params']['NEED_TOKEN'] = false;
                        var apiurl = '/api/index.php?r=project/auth/get-org-application-list/';
                        if (angular.isObject(search)) {
                            apiurl = url.addParam(apiurl, search);
                        } else {
                            apiurl += search
                        }
                        return $http.get(apiurl, data);
                    },
                    saveNewProjData: function (data, search) {
                        search = search || '';
                        data = data || {}
                        data['NEED_TOKEN'] = false;
                        var apiurl = '/api/index.php?r=project/project/create-project';
                        if (angular.isObject(search)) {
                            apiurl = url.addParam(apiurl, search);
                        } else {
                            apiurl += search
                        }
                        data = $.extend(data, {"USE_FORM_DATA": false});
                        return $http.post(apiurl, data);
                    },
                    checkCanAddPeriod: function (data, search) {
                        search = search || '';
                        data = data || {};
                        data['NEED_TOKEN'] = false;
                        var apiurl = '/api/index.php?r=project/project/check-can-add-sub-proj';
                        if (angular.isObject(search)) {
                            apiurl = url.addParam(apiurl, search);
                        } else {
                            apiurl += search
                        }
                        data = $.extend(data, {"USE_FORM_DATA": false});
                        return $http.post(apiurl, data);
                    },
                    checkProjNameCanUse: function (data, search) {
                        search = (search || '') + '&rnd=' + (new Date()).getTime();
                        data = data || {};
                        data['params'] = data['params'] || {};
                        data['params']['NEED_TOKEN'] = false;
                        return $http.get('/api/index.php?r=project/project/check-project-name-exist' + search, data)
                    }

                }
            }
        ])
        .directive('projNameAllow',
        ['projectService', function (service) {
            return {
                require: 'ngModel',
                link: function (scope, element, attrs, ngModel) {
                    function setAsAvailable(bool) {
                        ngModel.$setValidity('projNameAllow', bool);
                        //$(element).blur().focus();
                    }

                    function checkProjAction(value) {
                        if (!value || value.length == 0) {
                            return;
                        }

                        var queryString = "&projectName=" + value +'&organizationId='+(scope.belongsCompany.id||scope.parent.orgId)+'&parentGUID='+(scope.addProjectPeriod_puid||null);
                        service.checkProjNameCanUse({}, queryString).then(function (res) {
                            if (res && res.data.retCode == 0) {
                                ischecking = true;
                                setAsAvailable(!res.data.data);
                            }
                        });

                        return value;
                    }

                    $(element).on('blur',function(){
                        checkProjAction(ngModel.$modelValue)
                    });

                    //ngModel.$parsers.push(checkProjAction);
                }
            }
        }])
        .controller('ProjectController', [
            '$scope',
            '$q',
            '$timeout',
            'projectService',
            function ($scope, $q, $timeout, service) {
                service.getOrgList({
                    success: function (res) {
                        $scope.orgList = res.data;
                    }
                });

                $scope.showOrgList = function (orgList) {
                    //左侧组织名称
                    var $orgTree = $('#org_tree');
                    $orgTree.tree("destroy");
                    $orgTree.tree({
                        data: orgList,
                        dragAndDrop: false,
                        useContextMenu: false,
                        autoOpen: 0, //展开级别
                        onCreateLi: function (node, $li) {
                        },
                        //是否可以移动
                        onCanMove: function (node) {
                            return false;
                        },
                        //是否可以移动到
                        onCanMoveTo: function (moved_node, target_node, position) {
                            //只能在同级节点中移动
                            return false;
                        },
                        //移动句柄
                        onIsMoveHandle: function ($ele) {
                            return false;
                        }
                    })
                        .on('tree.click', function (event) {
                            if (event.node && event.node.id) {
                                $scope.orgId = event.node.id
                                $scope.searchProjectList($scope.orgId);
                            }
                        });

                    $orgTree.find("li:eq(0)").find("div").eq(0).trigger('click');
                }

                var formatOrgList = function (orgList) {
                    for (var i = 0, len = orgList.length; i < len; i++) {
                        var org = orgList[i];
                        org.children = org.childNodes;
                        if (org.children && org.children.length) {
                            org.children = arguments.callee(org.children);
                        }
                    }
                    return orgList;
                };

                var formatProjectList = function (projectList) {
                    for (var i = 0, len = projectList.length; i < len; i++) {
                        var project = projectList[i];
                        project.children = project.childNodes;
                        project.name = project.ProjName;
                        project.id = project.p_projectId;
                        //上移、下移的时候要传对应id
                        if (i === 0) {
                            project.prev = null;
                        } else {
                            project.prev = projectList[i - 1].p_projectId;
                        }
                        if (i === len - 1) {
                            project.next = null;
                        } else {
                            project.next = projectList[i + 1].p_projectId;
                        }
                        if (project.children && project.children.length) {
                            project.children = arguments.callee(project.children);
                        }
                    }
                    return projectList;
                };

                $scope.$watch('orgList', function (orgList) {
                    $timeout(function () {
                        if (orgList) {
                            orgList = formatOrgList(orgList);
                            orgList[0].checked = true;
                            $scope.showOrgList(orgList);
                        }
                    }, 20);
                });

                $scope.$watch('projectList', function (projectList) {
                    if (projectList) {
                        projectList = formatProjectList(projectList);
                        $scope.showProjectList(projectList);
                    }
                });

                $scope.searchProjectList = function (orgId) {
                    service.searchProjectList({
                        search: {
                            organizationId: orgId
                        },
                        success: function (res) {
                            $scope.projectList = res.data;
                        },
                        fail: function (res) {
                            //ui.showErrTip(res.errMsg);
                        }
                    });
                };

                $scope.showProjectList = function (projectList) {

                    //右侧项目列表
                    var $orgProjTree = $('#org_proj_tree');
                    $orgProjTree.tree("destroy");
                    $orgProjTree.tree({
                        data: projectList,
                        dragAndDrop: false,
                        useContextMenu: false,
                        autoOpen: 0, //展开级别
                        onCreateLi: function (node, $li) {

                            var htmlBuf = [];
                            if (node.parentGUID && node.IsDefault === '1') {
                                htmlBuf.push('<span class="c-white" style="background-color:#ff7713; padding:0 5px; margin-left:10px;">默认分期</span>');
                            }
                            htmlBuf.push('<div class="jqtree-btn" style="width:160px;right: 320px;background:none;">');
                            if (node.next !== null) {
                                htmlBuf = htmlBuf.concat([
                                    '<a href="javascript:;" title="下移" rel="movedown">',
                                    '<i class="icon-op icon-op-down">&nbsp;</i>',
                                    '</a>'
                                ]);
                            }
                            if (node.prev !== null) {
                                htmlBuf = htmlBuf.concat([
                                    '<a href="javascript:;" title="上移" rel="moveup">',
                                    '<i class="icon-op icon-op-up">&nbsp;</i>',
                                    '</a>'
                                ])
                            }
                            htmlBuf = htmlBuf.concat([
                                '</div>',
                                '<div class="fr permission p-0000200101-00" style="width: 300px;border-left: 1px solid #ccc;padding-bottom: 1px;">',
                                '<a href="javascript:;" title="编辑" rel="edit" class="mt5 c-orange permission p-0000200101-02-inline" style="padding-left: 10px;">编辑</a>'
                            ]);

                            if (!node.parentGUID) {
                                htmlBuf = htmlBuf.concat([
                                    '<a href="javascript:;" title="新增分期" rel="add" class="mt5 c-orange permission p-0000200101-01-inline" style="padding-left: 10px;">新增分期</a>'
                                ])
                            }

                            htmlBuf.push('<a href="javascript:;" title="删除" rel="delete" class="mt5 c-orange permission p-0000200101-03-inline" style="padding-left: 10px;">删除</a>');

                            if (node.parentGUID && !node.IsDefault) {
                                '<a href="javascript:;" title="设置默认分期" rel="setperiod" class="mt5 c-orange permission p-0000200101-02-inline">设置默认分期</a>'
                            }

                            htmlBuf.push('</div>');

                            $li.find(".jqtree-element").append(htmlBuf.join(''));
                        },
                        //是否可以移动
                        onCanMove: function (node) {
                            return false;
                        },
                        //是否可以移动到
                        onCanMoveTo: function (moved_node, target_node, position) {
                            //只能在同级节点中移动
                            return false;
                        },
                        //移动句柄
                        onIsMoveHandle: function ($ele) {
                            return false;
                        }
                    }).on(
                        'tree.click',
                        function (event) {
                            if (event && event.click_event) {
                                var target = event.click_event.target;
                                var rel = $(target).attr('rel') || $(target).parent().attr('rel');

                                if (rel && event.node && event.node.id) {
                                    var projId = event.node.id;
                                    switch (rel) {
                                        case "moveup":
                                            $scope.moveUp(projId, event.node.prev);
                                            break;
                                        case "movedown":
                                            $scope.moveDown(projId, event.node.next);
                                            break;
                                        case "delete":
                                            $scope.deleteProject(projId);
                                            break;
                                        case "setperiod":
                                            $scope.setDefaultPeriod(projId);
                                            break;
                                        case "edit":
                                            $scope.editProject(projId);
                                            break;
                                        case "add":
                                            $scope.addProjectPeriod(projId);
                                            break;
                                    }

                                }
                            }

                        }
                    );
                }

                $scope.moveUp = function (projId, prev) {
                    service.moveProject({
                        data: {
                            sortDescProjectId: prev,
                            sortAscProjectId: projId
                        },
                        success: function (res) {
                            $scope.searchProjectList($scope.orgId);
                        },
                        fail: function (res) {
                            //ui.showErrTip(res.errMsg);
                        }
                    })
                };

                $scope.moveDown = function (projId, next) {
                    service.moveProject({
                        data: {
                            sortDescProjectId: projId,
                            sortAscProjectId: next
                        },
                        success: function (res) {
                            $scope.searchProjectList($scope.orgId);
                        },
                        fail: function (res) {
                            //ui.showErrTip(res.errMsg);
                        }
                    })
                                                       
                };

                $scope.deleteProject = function (projId) {
                    var deleteProject = function () {
                        service.deleteProject({
                            data: {
                                projectId: projId
                            },
                            success: function (res) {
                                $scope.searchProjectList($scope.orgId);
                            },
                            fail: function (res) {
                                //ui.showErrTip(res.errMsg);
                            }
                        });
                    }
                    require.async("dialog", function (dialog) {
                        dialog({
                            title: '删除',
                            fixed: true,
                            content: "确定删除该项目吗？",
                            width: 350,
                            okValue: '确定',
                            cancelValue: "取消",
                            cancelDisplay: true,
                            ok: deleteProject,
                            cancel: function(){return true;}
                        }).showModal();
                    }); 
                };

                $scope.setDefaultPeriod = function (projId) {
                    service.setDefaultPeriod({
                        data: {
                            projectId: projId
                        },
                        success: function (res) {
                            $scope.searchProjectList($scope.orgId);
                        },
                        fail: function (res) {
                            //ui.showErrTip(res.errMsg);
                        }
                    })
                };

                $scope.searchObj = util.getQueryParams(location.search);


                $scope.editProject = function (projId) {
                    location.href = "house_manage.shtml?projId=" + projId + "&type=edit";
                };

                $scope.addProjectPeriod = function (projId) {
                    var data = {projectId: projId};
                    service.checkCanAddPeriod(data).then(function (res) {
                        if (res && res.data.retCode == 0) {
                            $scope.addProjectPeriod_puid = projId;
                            $timeout(function () {
                                $('#addProjBtn').click();
                            }, 20);
                        }
                    });
                };

                $scope.beforeShowERPProject = function (dialog, dialogScope) {

                    var data = {};
                    service.checkCanBind(data).then(function (res) {
                        if (res.data.retCode == 0) {
                            dialog.showModal();
                            $scope.showERPProject();
                        }
                    });
                    return false;
                };


                $scope.select_org_id = '';
                $scope.showERPCompany = function () {
                    var data = {}, deferred = $q.defer();

                    service.getErpCompanies(data).then(function (res) {
                        rdata = res.data.data;
                        if (res.data.retCode == 0) {
                            //左侧组织名称
                            $orgTree = $('#org_name_tree');
                            $orgTree.tree("destroy");
                            $orgTree.tree({
                                data: rdata,
                                dragAndDrop: false,
                                useContextMenu: false,
                                autoOpen: 0, //展开级别
                                onCreateLi: function (node, $li) {
                                    var id = node.id;
                                    $li.find(".jqtree-element").attr('id', node.id);
                                },
                                //是否可以移动
                                onCanMove: function (node) {
                                    return false;
                                },
                                //是否可以移动到
                                onCanMoveTo: function (moved_node, target_node, position) {
                                    //只能在同级节点中移动
                                    return false;
                                },
                                //移动句柄
                                onIsMoveHandle: function ($ele) {
                                    return false;
                                }
                            }).on('tree.click', function (event) {
                                var node = event.node, projList;
                                event.preventDefault();
                                var node = event.node;
                                var checked = getCheckedErpList();
                                if (checked.length > 0) {
                                    dialog({
                                        title: '提示',
                                        fixed: true,
                                        content: "<h4>不允许同时绑定不同组织下的项目！</h4>",
                                        width: 350,
                                        okValue: '确定',
                                        cancelDisplay: false,
                                        ok: function () {
                                        },
                                        cancel: function () {
                                        }
                                    }).showModal();
                                    return;
                                } else {
                                    $orgTree.find('.jqtree-selected').removeClass('jqtree-selected');
                                    $("#" + node.id).closest('li').addClass('jqtree-selected');
                                    $scope.select_org_id = node.id;
                                    getErpProjListReq(node.id);
                                }
                            });
                            deferred.resolve(res.data)
                        }
                    });

                    return deferred.promise;

                };

                $scope.showERPProject = function (dialog, dialogScope) {
                    $scope.showERPCompany().then(function (res) {
                            var data = {}, companyId;
                            if ($scope.select_org_id) {
                                companyId = $scope.select_org_id;
                            } else {
                                companyId = res.data[0] && res.data[0].id;
                            }
                            if(!companyId){
                                return;
                            }
                            var node = $orgTree.tree('getNodeById', companyId);
                            node.checked = true;
                            $("#" + node.id).closest('li').addClass('jqtree-selected');
                            getErpProjListReq(companyId);
                        }
                    )
                };

                var $erp_proj_tree;

                function getCheckedErpList() {
                    return $erp_proj_tree.find("input[type=checkbox]:checked");
                }

                function checkSelectedValid(chk) {
                    //不允许同时绑定ERP的两个项目
                    var checked = getCheckedErpList(), flag = false;
                    checked.each(function () {
                        var cur_ckbox = $(this);
                        var cur_id = $(chk.closest("li.has-child").find('input.has-child')[0]).attr('id');
                        if (cur_id != $(cur_ckbox.closest("li.has-child").find('input.has-child')[0]).attr('id')||(chk.attr('level')==2&&cur_id!=chk.attr('id'))) {
                            flag = true;
                        }
                    });
                    return flag
                }

                function getErpProjListReq(id) {

                    service.getErpProjectsList({}, '&id=' + id).then(function (res) {
                        if (res.data.retCode == 0) {
                            //右侧项目列表
                            $erp_proj_tree = $('#erp_proj_tree');
                            $erp_proj_tree.tree("destroy");
                            $erp_proj_tree.tree({
                                data: res.data.data,
                                dragAndDrop: false,
                                useContextMenu: false,
                                autoOpen: 0, //展开级别
                                onCreateLi: function (node, $li) {
                                    var id = node.id,level = node.Level, hasChildClass = node.children.length > 0 ? 'has-child' : '';
                                    $li.addClass(hasChildClass).find(".jqtree-element").append("<span class='projcode'>" + node.ProjCode + "</span>");
                                    level == 3 ? $li.find('.jqtree-title').css({'margin-left':'40px'}):'';
                                    $li.find(".jqtree-element").before("<span class='checkbox proj_tree'><input id='" + id +"' level='" + level
                                        + "' class='" + hasChildClass + "' type='checkbox' value=''><label for='" + id + "'>&nbsp;</label></span>");
                                },
                                //是否可以移动
                                onCanMove: function (node) {
                                    return false;
                                },
                                //是否可以移动到
                                onCanMoveTo: function (moved_node, target_node, position) {
                                    //只能在同级节点中移动
                                    return false;
                                },
                                //移动句柄
                                onIsMoveHandle: function ($ele) {
                                    return false;
                                }
                            }).on(
                                'tree.click',
                                function (event) {
                                    event.preventDefault();
                                    var node = event.node, checkbox = $('#' + node.id), isCheckedAllSub;
                                    if (!checkbox.prop("checked") && checkSelectedValid(checkbox)) {
                                        dialog({
                                            title: '提示',
                                            fixed: true,
                                            content: "<h4>不允许同时绑定ERP的两个项目！</h4>",
                                            width: 350,
                                            okValue: '确定',
                                            cancelDisplay: false,
                                            ok: function () {
                                            },
                                            cancel: function () {
                                            }
                                        }).showModal();
                                        return;
                                    }

                                    if (checkbox.prop("checked")) {
                                        checkbox.prop("checked", false);
                                        node.checked = false;
                                    } else {
                                        checkbox.prop("checked", "checked");
                                        node.checked = true;
                                    }
                                    //父级节点则子节点全部勾选
                                    if (node.children.length > 0) {
                                        checkbox.closest(".jqtree-folder").find("input[type=checkbox]").prop("checked", checkbox.prop("checked"));
                                        _.each(node.children, function (item) {
                                            item.checked = false;
                                        })
                                    }
                                    //子节点全部勾选则父节点勾选
                                    isCheckedAllSub = _.every(node.parent.children, function (item) {
                                        return item.checked == true;
                                    })
                                    if (isCheckedAllSub) {
                                        $('#' + node.parent.id).prop("checked", "checked");
                                        node.parent.checked = true;
                                    }

                                    if (!checkbox.prop("checked")) {
                                        $('#' + node.parent.id).prop("checked", false);
                                        node.parent.checked = false;
                                    }
                                }
                            )
                            //选中回现
                            _.each($scope.bindErpList, function (item) {
                                $('#' + item.Erp_ProjectGUID).prop("checked", "checked");
                            });
                        }
                    })

                }


                $scope.closeAddDialog = function () {
                    $scope.addProjectPeriod_puid = null;
                }

                $scope.showAddProjectDialog = function (dialog, dialogScope) {
                    dialog.button([]);
                    //初始化区域选择控件
                    var address = $('#address');
                    address.val('');
                    areabox.init(address, {
                        title: '选择省份',
                        asyncDataApi: {
                            province: '/api/index.php?r=common/region/get-all-province',
                            city: '/api/index.php?r=common/region/get-all-city-by-province-id',
                            district: '/api/index.php?r=common/region/get-all-area-by-city-id'
                        },
                        showRange: {start: 1, end: 3},
                        placement: "bottom",
                        callBack: function (dom) {
                            dialogScope.address = dom.val();
                            $scope.$apply();
                        }
                    });

                    function fixedData(data) {
                        angular.forEach(data, function (item) {
                            item.children = item.childNodes;
                            fixedData(item.childNodes);
                        });
                        return data;
                    }

                    var $tree = $("#tree_table");
                    $scope.bindErpList = [];

                    //所属公司
                    service.queryAllOrganizations({
                        success: function (res) {
                            if (res && res.retCode == 0) {
                                $tree.tree({
                                    data: fixedData(res.data),
                                    dragAndDrop: false,
                                    useContextMenu: false,
                                    autoOpen: 0, //展开级别
                                    onCreateLi: function (node, $li) {
                                    },
                                    //是否可以移动
                                    onCanMove: function (node) {
                                        return false;
                                    },
                                    //是否可以移动到
                                    onCanMoveTo: function (moved_node, target_node, position) {
                                        //只能在同级节点中移动
                                        return false;
                                    },
                                    //移动句柄
                                    onIsMoveHandle: function ($ele) {
                                        return false;
                                    }
                                }).on(
                                    'tree.click',
                                    function (event) {
                                        var node = event.node;
                                        dialogScope.belongsCompany = node;
                                        dialogScope.isTreeCollapse = false;
                                        $('input[name=projectName]').blur();
                                        $scope.$apply();
                                    }
                                );
                                var orgNode = $('#org_tree').tree('getNodeById', $scope.orgId);
                                dialogScope.belongsCompany = orgNode;
                            }
                        }
                    });
                    dialogScope.isTreeCollapse = false;
                    dialogScope.cur_step = 1;

                    dialogScope.toggleTreeCombo = function () {
                        dialogScope.isTreeCollapse = !dialogScope.isTreeCollapse;
                        $(window).on('click', function (event) {
                            var target = $(event.target);
                            if ($tree.parent().has(target).length < 1) {
                                dialogScope.isTreeCollapse = false;
                            }
                            $scope.$apply();
                        });
                    };
                    dialogScope.bindErpList = $scope.bindErpList;
                    dialogScope.belongsCompany = null;
                    dialogScope.bindERPProject = $scope.bindERPProject;
                    dialogScope.showERPProject = $scope.showERPProject;
                    dialogScope.beforeShowERPProject = $scope.beforeShowERPProject;
                    dialogScope.addProjectPeriod_puid = $scope.addProjectPeriod_puid;
                    dialogScope.prevStep = function () {
                        dialogScope.cur_step--;
                        showSetpContent(dialogScope.cur_step,1);
                    };
                    dialogScope.nextStep = function (formValid) {
                        $timeout(function () {
                            $('#submitBtn').click();
                        }, 20);
                        $timeout(function () {
                            if (dialogScope.cur_step == 1 && !formValid) {
                                return;
                            } else {
                                dialogScope.cur_step++;
                            }
                            if (dialogScope.cur_step == 3 && !dialogScope.projAuthList) {
                                getProjBindInfo();
                            }
                            showSetpContent(dialogScope.cur_step,-1);
                        }, 500);
                    };
                    dialogScope.closeAddDialog = function () {
                        $scope.addProjectPeriod_puid = null;
                        dialog.close();
                    };

                    function showSetpContent(cur,pos){
                        var arr = [
                            '.first-step-warp',
                            '.second-step-warp',
                            '.third-step-warp'];
                        $(arr[cur-1]).show();
                        $(arr[cur-1+pos]).hide();
                    }
                    $('.first-step-warp').show();
                    $('.second-step-warp').hide();
                    $('.third-step-warp').hide();

                    function setDefaultBindErpProj() {
                        var noDefault = _.every(dialogScope.bindErpList, function (item) {
                            return item.DefaultProject != 1;
                        });

                        if (noDefault && dialogScope.bindErpList.length > 0) {
                            dialogScope.bindErpList[0].DefaultProject = 1;
                        }
                    }


                    //新模式 掌上售楼处必须有一个绑定项才能绑其他的
                    dialogScope.check_can_bind = function () {
                        var binded = [];
                        _.each(dialogScope.projAuthList, function (item) {
                            if (item.isZsslc) {
                                binded = _.filter(item.contracts, function (cont_item) {
                                    return cont_item.binding == 1;
                                });
                            }
                        });
                        return binded;
                    };
                    //新模式 掌上售楼处的最后一项取消绑定时其它的必须都取消
                    dialogScope.check_can_cancel = function () {
                        var binded = dialogScope.check_can_bind(), otherBinded = [];
                        if (binded.length == 1) {
                            _.each(dialogScope.projAuthList, function (item) {
                                if (!item.isZsslc) {
                                    otherBinded = otherBinded.concat(_.filter(item.contracts, function (cont_item) {
                                        return cont_item.binding == 1;
                                    }));
                                }
                            });
                        }
                        return otherBinded;

                    };

                    //绑定ERP项目添加到列表
                    dialogScope.bindERPProject = function () {
                        var selectedNodes = getCheckedErpList(), nodesList = [];
                        dialogScope.bindErpList =[];
                        _.each(selectedNodes, function (chk) {
                            var node = $erp_proj_tree.tree('getNodeById', $(chk).attr('id'));
                            if (node.children.length < 1) {
                                nodesList.push({
                                    Erp_ProjectName: node.name,
                                    Erp_ProjectGUID: node.ProjGUID,
                                    type: 'add',
                                    Erp_ParentProjectGUID: node.parent&&node.parent.parent ? node.parent.ProjGUID:null
                                })
                            }
                        });

                        _.each(nodesList, function (item) {
                            if (_.indexOf(_.pluck(dialogScope.bindErpList, 'Erp_ProjectGUID'), item.Erp_ProjectGUID) < 0) {
                                dialogScope.bindErpList.push(item);
                            }
                        });
                        $scope.bindErpList = dialogScope.bindErpList;
                        //新添加的ERP项目设置第一个为默认
                        setDefaultBindErpProj();

                    };
                    //设为默认
                    dialogScope.setDefault = function (item) {
                        _.each(dialogScope.bindErpList, function (item) {
                            if (item.DefaultProject == 1) {
                                item.DefaultProject = 0;
                            }
                        });
                        item.DefaultProject = 1;
                    };

                    dialogScope.cancelBind = function (item) {
                        dialogScope.bindErpList = _.filter(dialogScope.bindErpList, function (listItem) {
                            return listItem.Erp_ProjectGUID != item.Erp_ProjectGUID;
                        });
                        $scope.bindErpList =  dialogScope.bindErpList;
                        setDefaultBindErpProj();
                    };


                    function getProjBindInfo() {
                        var data = {};
                        service.getAuthInfo(data).then(function (res) {
                            if (res && res.data && res.data.retCode == 0) {
                                dialogScope.projAuthList = res.data.data.data;
                                dialogScope.cur_bind_mode = res.data.data.isUpgrade;
                                _.each(dialogScope.projAuthList, function (item) {
                                    _.each(item.contracts, function (cont_item) {
                                        cont_item.type = 'init';
                                    });
                                });
                            }
                        });
                    }

                    $scope.continue_bindAuth = function(item,cont_item){
                        var binded = dialogScope.check_can_bind();
                        if (dialogScope.cur_bind_mode && !item.isZsslc && !binded.length > 0) {//非掌上售楼处
                            return;
                        }
                        cont_item.binding = 1;
                        cont_item.use_num++;
                        if (cont_item.type == 'delete') {
                            cont_item.type = 'init';
                        } else if (cont_item.type = 'init') {
                            cont_item.type = 'add';
                        }

                    }


                    //绑定授权
                    dialogScope.bindAuth = function (item, cont_item) {
                        if(item.Application=='5030'){
                            util.confirm('绑定云Call客前，请检查并确认项目已经绑定移动销售及全民营销两个应用，是否继续绑定?',
                                {
                                    ok: function(){
                                        $scope.continue_bindAuth(item,cont_item);
                                    },
                                    cancel: function () {
                                    },
                                    okValue:'继续绑定'
                                })
                        }else{
                            $scope.continue_bindAuth(item,cont_item);
                        }

                    };

                    //取消绑定
                    dialogScope.cancelAuth = function (item, cont_item) {
                        var binded = dialogScope.check_can_cancel();
                        if (dialogScope.cur_bind_mode && item.isZsslc && binded.length > 0) {//掌上售楼处
                            return;
                        }
                        cont_item.binding = 0;
                        cont_item.use_num--;
                        if (cont_item.type == 'add') {
                            cont_item.type = 'init';
                        } else if (cont_item.type == 'init') {
                            cont_item.type = 'delete';
                        }
                    };

                    //填写项目信息完成，提交数据
                    dialogScope.completeNewProject = function () {
                        var erpProjList = [];
                        _.each(dialogScope.bindErpList, function (item) {
                            if (item.type != 'init') {
                                erpProjList.push(_.pick(item, 'Erp_ParentProjectGUID', 'Erp_ProjectGUID', 'p_Project2ErpProjectId', 'Erp_ProjectName', 'ProjectGUID', 'type', 'DefaultProject'));
                            }
                        });

                        var authData = [];
                        _.each(dialogScope.projAuthList, function (item) {
                            _.each(item.contracts, function (cont_item) {
                                if (cont_item.type != 'init') {
                                    authData.push({
                                        ApplicationCode: item.Application,
                                        AuthorizeId: cont_item.authorize_id,
                                        type: cont_item.type
                                    })
                                }
                                ;
                            })
                        });

                        var data = {
                            projectInfo: {
                                ProjName: dialogScope.projectName,
                                BUName: dialogScope.belongsCompany.name,
                                BUGUID: dialogScope.belongsCompany.id,
                                myscrm_ProvinceId: address.attr('province'),
                                myscrm_CityId: address.attr('city'),
                                myscrm_AreaId: address.attr('district')
                            },
                            erpProject: erpProjList,
                            auth: authData
                        };
                        if ($scope.addProjectPeriod_puid) {
                            data.projectInfo.parentGUID = $scope.addProjectPeriod_puid
                        }
                        //保存数据
                        service.saveNewProjData(data).then(function (res) {
                            if (res && res.data.retCode == 0) {
                                ui.showSucTip('操作成功');
                                dialog.close();
                                $timeout(function(){
                                    service.getOrgList({
                                        success: function (res) {
                                            $scope.orgList = res.data;
                                        }
                                    });
                                },2500)

                            }

                        });
                    };
                }
            }
        ]);

    angular.element(document).ready(function () {
        angular.bootstrap(document, ['housesProject']);
    })

});
